package com.nut.spp.jbb.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.nut.spp.common.Result;
import com.nut.spp.entity.JbbMessageRecord;
import com.nut.spp.jbb.JbbMsgService;
import com.nut.spp.mapper.JbbMessageRecordMapper;
import com.nut.spp.service.MemberCouponService;
import com.nut.spp.service.PayService;
import com.nut.spp.service.ShopService;
import com.nut.spp.util.JacksonUtils;
import com.nut.spp.util.StringTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
@Slf4j
public class JbbMsgServiceImpl implements JbbMsgService {

    @Autowired
    private ShopService shopService;

    @Autowired
    private PayService payService;

    @Autowired
    private MemberCouponService memberCouponService;

    @Autowired
    private JbbMessageRecordMapper jbbMessageRecordMapper;

    @Override
    public Result process(String message) {

//        {"bizNo":"24100910002","object":"corpMember","auditDesc":"great","createdTime":"2024-09-09","settleAccountId":"eee","status":"SUCCEEDED"}

//        {"payNo":"UN202410221298324565512163328","orderNo":"941022100005","createdTime":"20241022163818","description":"支付订单:941022100005","payChannel":"alipay_qr","endTime":"20241022163825","payAmt":"0.01","payStatus":"succeeded","transactionId":"002212024102216381810694719442575507456","object":"payment"}

//        {"data":[{"orderNumber":"WKP10101091650539788","phone":"13086881373","payAmt":19980.00}],"object":"coupon"}

        if (StringTool.isEmpty(message)) {
            return Result.ok();
        }

        JsonNode obj = JacksonUtils.toObj(message);

        String type = obj.get("object").asText();

        JbbMessageRecord record = new JbbMessageRecord();
        record.setType(type);
        record.setContent(message);
        jbbMessageRecordMapper.insert(record);

        if ("corpMember".equals(type)) {
            shopService.jbbCorpCreate(obj);
        } else if ("payment".equals(type)) {
            payService.callback(obj, message);
        } else if ("cash".equals(type)) {

        } else if ("coupon".equals(type)) {
            memberCouponService.callback(obj, message);
        }

        return Result.ok();
    }

    @Override
    public Result processRecord(Integer id) {

        JbbMessageRecord record = jbbMessageRecordMapper.selectById(id);
        String type = record.getType();
        JsonNode obj = JacksonUtils.toObj(record.getContent());

        if ("corpMember".equals(type)) {
            shopService.jbbCorpCreate(obj);
        } else if ("payment".equals(type)) {
            payService.callback(obj, record.getContent());
        } else if ("cash".equals(type)) {

        } else if ("coupon".equals(type)) {
            memberCouponService.callback(obj, record.getContent());
        }
        return Result.ok();
    }


}